using Godot;
using System.Collections.Generic;

namespace AndroidUnevenRoadGame.Game
{
    /// <summary>
    /// 负责根据随机种子生成关卡路线。
    /// </summary>
    public sealed class MapSystem
    {
        private readonly RandomNumberGenerator _rng;

        public IReadOnlyList<MapFloor> Floors => _floors;
        private readonly List<MapFloor> _floors = new();

        public MapSystem(RandomNumberGenerator rng)
        {
            _rng = rng;
        }

        public void GenerateFloors(uint seed, int floorCount)
        {
            _floors.Clear();
            _rng.Seed = seed;

            for (int i = 0; i < floorCount; i++)
            {
                var floor = new MapFloor
                {
                    Index = i + 1,
                    Nodes = new List<MapNode>()
                };

                for (int j = 0; j < 4; j++)
                {
                    floor.Nodes.Add(new MapNode
                    {
                        Type = RollNodeType(),
                        Connections = new List<int>()
                    });
                }

                if (i > 0)
                {
                    ConnectFloors(_floors[^1], floor);
                }

                _floors.Add(floor);
            }
        }

        private MapNodeType RollNodeType()
        {
            var roll = _rng.Randf();
            if (roll < 0.4f) return MapNodeType.Battle;
            if (roll < 0.6f) return MapNodeType.Elite;
            if (roll < 0.75f) return MapNodeType.Event;
            if (roll < 0.9f) return MapNodeType.Shop;
            return MapNodeType.Hanfu;
        }

        private static void ConnectFloors(MapFloor previous, MapFloor current)
        {
            for (int i = 0; i < previous.Nodes.Count; i++)
            {
                var connections = previous.Nodes[i].Connections;
                connections.Clear();
                connections.Add(Mathf.Clamp(i - 1, 0, current.Nodes.Count - 1));
                connections.Add(i);
                connections.Add(Mathf.Clamp(i + 1, 0, current.Nodes.Count - 1));
            }
        }
    }

    public sealed class MapFloor
    {
        public int Index { get; init; }
        public List<MapNode> Nodes { get; init; } = new();
    }

    public sealed class MapNode
    {
        public MapNodeType Type { get; init; }
        public List<int> Connections { get; init; } = new();
    }

    public enum MapNodeType
    {
        Battle,
        Elite,
        Boss,
        Event,
        Shop,
        Hanfu
    }
}

